package cn.usts.edu.setClassMethod06;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author ：fly
 * @description: 利用反射来  实例化对象,调用功能方法,设置属性
 *                 newInstance() 的本质是利用无参构造器,构造对象的,没有无参构造器,是无法构造的
 *                 参数用private修饰的要 修改程序安全监测为ture,默认false是开启检测
 * @date ：2021/10/28 15:51
 */
public class SetClass {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        // 获取Class对象
        Class<?> c1 = Class.forName("cn.usts.edu.setClassMethod06.User");
        // 反射实例化对象 Object o = c1.newInstance();
        User user = (User) c1.newInstance();//将Object对象转化成我们的User对象
        System.out.println(user);

        // 通过构造器构造
        Constructor<?> declaredConstructor = c1.getDeclaredConstructor(int.class,String.class);
        User user1 = (User) declaredConstructor.newInstance(15, "小明");
        System.out.println("反射构造器构造"+user1);

        //通过反射调用方法
        Method method03 = c1.getDeclaredMethod("method03", String.class);
        method03.setAccessible(true); //  参数用private修改的要 修改程序安全监测为ture,默认false是开启检测
        method03.invoke(user1,"利用反射调用方法");//invoke激活, (操作对象,方法中的参数)

        // 通过反射设置属性
        Field name = c1.getDeclaredField("name");
        Field age = c1.getDeclaredField("age");
        age.setAccessible(true);
        name.setAccessible(true); // 每修改一个就要设置一个
        name.set(user1,"反射直接修改属性的值");
        age.set(user1,18);
        System.out.println(user1.getAge());
        System.out.println(user1.getName());



    }
}

// pojo 实体类
class User {
    public int age;
    private String name;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public User() {
    }

    public User(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public void method01(){
        System.out.println("method01");
    }

    public void method01(int age){
        System.out.println("method02"+this.age+age);
    }

    private void method03(String name){
        System.out.println(name+"method03"+this.name);
    }

    @Override
    public String toString() {
        return "User{" +
                "age=" + age +
                ", name=" + name +
                '}';
    }
}
